import { ethers } from "ethers";

export class WalletConnector {
  private static provider: ethers.providers.Web3Provider | null = null;
  private static signer: ethers.Signer | null = null;
  private static account: string | null = null;

  // 初始化钱包连接
  static async connectWallet(): Promise<boolean> {
    if (typeof window.ethereum === "undefined") {
      console.error("No crypto wallet found. Please install MetaMask!");
      return false;
    }

    // 创建一个 Web3Provider 实例
    this.provider = new ethers.providers.Web3Provider(window.ethereum);
    try {
      // 请求连接钱包
      await window.ethereum.request({ method: "eth_requestAccounts" });
      this.signer = this.provider.getSigner();
      this.account = await this.signer.getAddress();
      // 连接指定网络
      this.getNetWork();
      // 监听账户和网络变化
      this.listenAccountChange();
      this.listenNetworkChange();

      return true;
    } catch (error) {
      console.error("Failed to connect wallet", error);
      return false;
    }
  }
  // 连接到指定的网路
  static async getNetWork() {
    const chainId = Number(import.meta.env.VITE_APP_CHAINID); // 替换为你需要的链 ID
    await this.provider.send("wallet_switchEthereumChain", [
      { chainId: `0x${chainId.toString(16)}` },
    ]);
  }
  // 获取当前连接的账户地址
  static getAccount(): string | null {
    return this.account;
  }

  // 获取当前 provider
  static getProvider(): ethers.providers.Web3Provider | null {
    return this.provider;
  }

  // 获取当前 signer
  static getSigner(): ethers.Signer | null {
    return this.signer;
  }

  // 监听账户变化
  private static listenAccountChange() {
    window.ethereum.on("accountsChanged", (accounts: string[]) => {
      if (accounts.length === 0) {
        console.log("Please connect to MetaMask.");
        this.account = null;
      } else {
        this.account = accounts[0];
        console.log("Account changed to:", this.account);
      }
    });
  }

  // 监听网络变化
  private static listenNetworkChange() {
    window.ethereum.on("chainChanged", (chainId: string) => {
      console.log("Network changed to:", chainId);
      // 可以在这里处理网络变化的逻辑
    });
  }
}
